<template>
  <div class="app-container">
    <el-row :gutter="24" class="mb8" >
        <el-col :span="4">
            <!-- 组织结构树组件 -->
            <orgstructure ref="org" @emitParentGlobalThis="emitParentGlobalThis" @updateSure="updateSure"></orgstructure>
        </el-col>
        <el-col :span="20"  style="border-left: 1px solid  rgba(240,240,240,1);">
            <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true">
                <el-form-item label="用户姓名" prop="nickname">
                    <el-input v-model="queryParams.nickname" placeholder="请输入" clearable size="small" style="width: 240px"
                            @keyup.enter.native="handleQuery"/>
                </el-form-item>
                <el-form-item label="用户手机号码" prop="mobile">
                    <el-input v-model="queryParams.mobile" placeholder="请输入" clearable size="small" style="width: 240px"
                            @keyup.enter.native="handleQuery"/>
                </el-form-item>
                <el-form-item label="用户账号" prop="username">
                    <el-input v-model="queryParams.username" placeholder="请输入" clearable size="small" style="width: 240px"
                            @keyup.enter.native="handleQuery"/>
                </el-form-item>
                <el-form-item label="下级组织用户" prop="code">
                    <!-- <el-input v-model="queryParams.code" placeholder="请输入角色标识" clearable size="small" style="width: 240px"
                            @keyup.enter.native="handleQuery"/> -->
                    <el-select v-model="queryParams.show" placeholder="请选择" style="width: 240px">
                      <el-option key="1" label="显示" :value="true"></el-option>
                      <el-option key="0" label="不显示" :value="false"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button v-preventReClick type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
                    <el-button v-preventReClick icon="el-icon-refresh" class="border-Blue" size="mini" @click="resetQuery">重置</el-button>
                </el-form-item>
                </el-form>

                <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                    <el-button v-preventReClick type="primary" size="mini" @click="handleAdd" :disabled="isClick"
                            v-hasPermi="['system:role:create']">新建用户</el-button>
                </el-col>
                <el-col :span="1.5">
                    <el-button v-preventReClick  plain="" size="mini" @click="handleExport" :loading="exportLoading"
                            v-hasPermi="['system:role:export']">批量导入用户</el-button>
                </el-col>
                 <el-col :span="1.5">
                    <el-button v-preventReClick  plain="" size="mini" :disabled="btnselectData.length == 0" @click="handlePersonChange" :loading="exportLoading"
                            v-hasPermi="['system:role:export']">人员变更</el-button>
                </el-col>
                 <el-col :span="1.5">
                    <el-button v-preventReClick  plain="" size="mini" :disabled="btnselectData.length == 0" @click="handlereg" :loading="exportLoading"
                            v-hasPermi="['system:role:export']">操作离职</el-button>
                </el-col>
                <div class="top-right-btn">
                  <el-button v-preventReClick type="text" icon="el-icon-copy-document" @click="Routerinsidepersonchange">变更人员记录</el-button>
                  <el-button v-preventReClick type="text" icon="el-icon-user" @click="Routerinsidereg">离职人员记录</el-button>
                </div>
                <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
                </el-row>

              <el-table ref="table" v-loading="loading" :data="userList" show-overflow-tooltip class="margin-top"  @select="handleSelectionChange">
                <el-table-column
                  type="selection"
                  width="55">
                </el-table-column>

                <el-table-column label="用户姓名" prop="nickname"  >
                <template v-slot="scope">
                     <span v-if="scope.row.isPluralistic" class="isPluralistic">兼</span>
                     <span>{{ scope.row.nickname }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="登录账号" prop="username" :show-overflow-tooltip="true"  />
                <el-table-column label="用户编码" prop="userCode" :show-overflow-tooltip="true" />
                <el-table-column label="用户手机号" prop="mobile" :show-overflow-tooltip="true"   />
                <el-table-column label="所属组织" prop="dept.name"  />
                <el-table-column label="用户状态" align="center" >
                    <template v-slot="scope">
                      <div v-if="scope.row.status == 0">在职</div>
                      <div v-if="scope.row.status == 1">离职</div>
                    </template>
                </el-table-column>
                <el-table-column label="创建时间" align="center" prop="createTime" >
                    <template v-slot="scope">
                    <span>{{ parseTime(scope.row.createTime) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" fixed="right"  class-name="small-padding fixed-width">
                    <template v-slot="scope">
                    <el-button v-preventReClick size="mini" type="text" @click="handleMenu('1',scope.row)">查看</el-button>
                    <span v-if="!scope.row.isPluralistic" class="spans">|</span>
                    <el-button v-if="!scope.row.isPluralistic" v-preventReClick size="mini" type="text" @click="handleMenu('2',scope.row)">编辑</el-button>
                    <span v-if="!scope.row.isPluralistic" class="spans">|</span>
                    <el-dropdown v-if="!scope.row.isPluralistic" >
                      <el-button v-preventReClick type="text">
                        更多<i class="el-icon-arrow-down el-icon--right"></i>
                      </el-button>
                      <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item>
                          <el-button v-preventReClick size="mini" type="text" @click="handleedit(scope.row)"
                                v-hasPermi="['system:role:delete']">重置登录密码</el-button>
                        </el-dropdown-item>
                        <el-dropdown-item>
                              <el-button v-preventReClick size="mini" type="text" @click="handleDelete(scope.row)"
                                v-hasPermi="['system:role:delete']">删除</el-button>
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </el-dropdown>
                
                    <!-- <el-button v-preventReClick size="mini" type="text" @click="handleDataScope(scope.row)">更多</el-button> -->
                    </template>
                </el-table-column>
              </el-table>

                <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                            @pagination="getList"/>
        </el-col>
    </el-row>


    <!-- 添加或修改角色配置对话框 -->
    <Adduser ref="adduser" @getList="getList" ></Adduser>
    <!-- 操作离职组件 -->
    <Resignation ref="reg"></Resignation>
    <!-- 人员变更 -->
    <PersonChange ref="PersonChange"></PersonChange>
    <!-- 部门管理 -->
    <deptManage ref="deptM"></deptManage>
    <!-- 分配角色的数据权限对话框 -->
    <el-dialog title="分配数据权限" :visible.sync="openDataScope" width="500px" append-to-body>
      <el-form :model="form" label-width="80px">
        <el-form-item label="角色名称">
          <el-input v-model="form.name" :disabled="true" />
        </el-form-item>
        <el-form-item label="角色标识">
          <el-input v-model="form.code" :disabled="true" />
        </el-form-item>
        <el-form-item label="权限范围">
          <el-select v-model="form.dataScope">
            <el-option
              v-for="item in dataScopeDictDatas"
              :key="parseInt(item.value)"
              :label="item.label"
              :value="parseInt(item.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据权限" v-show="form.dataScope === SysDataScopeEnum.DEPT_CUSTOM">
          <el-checkbox :checked="!form.deptCheckStrictly" @change="handleCheckedTreeConnect($event, 'dept')">父子联动(选中父节点，自动选择子节点)</el-checkbox>
          <el-checkbox v-model="deptExpand" @change="handleCheckedTreeExpand($event, 'dept')">展开/折叠</el-checkbox>
          <el-checkbox v-model="deptNodeAll" @change="handleCheckedTreeNodeAll($event, 'dept')">全选/全不选</el-checkbox>
          <el-tree
            class="tree-border"
            :data="deptOptions"
            show-checkbox
            default-expand-all
            ref="dept"
            node-key="id"
            :check-strictly="form.deptCheckStrictly"
            empty-text="加载中，请稍后"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-preventReClick type="primary" @click="submitDataScope">确 定</el-button>
        <el-button v-preventReClick @click="cancelDataScope">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog 
    :title="titleUser"
    :visible.sync="dialogVisible"
    width="36%"
    >
    <div style="text-align: center;">
      <span v-if="titleUser == '确定重置用户密码？'">重置用户登录密码后，系统将给用户的邮箱，手机号发送新登录密码</span>
      <span v-if="titleUser == '确定删除此组织？'">删除后，该组织信息不可恢复</span>
      <span v-if="titleUser == '确认删除此用户？'&& onlyManger==false">您是否已确认该用户已无待办任务、无待签署任务？如果用户仍有未完成的任务，删除用户会导致未完成任务无法推进。</span>
      <span v-if="titleUser == '确认删除此用户？'&& onlyManger==true"> 该人员为集团管理员，请先设置其他人为该角色。</span>
    </div> 
    <span slot="footer" class="dialog-footer">
      <el-button v-preventReClick @click="dialogVisible = false">取 消</el-button>
      <el-button v-preventReClick type="primary" @click="update">确 定</el-button>
    </span>
    </el-dialog>
    <el-dialog 
        :title="titleShow"
        :visible.sync="dialogShow"
        width="36%"
        >
        <div style="text-align: center;">
          <span v-if="titleUser == '确定重置用户密码？'">重置用户登录密码后，系统将给用户的邮箱，手机号发送新登录密码</span>
          <span v-if="titleUser == '确认删除此用户？'&& onlyManger==false">您是否已确认该用户已无待办任务、无待签署任务？如果用户仍有未完成的任务，删除用户会导致未完成任务无法推进。</span>
          <span v-else> 该人员为集团管理员，请先设置其他人为该角色。</span>
        </div> 
        <span slot="footer" class="dialog-footer">
          <el-button v-preventReClick @click="dialogVisible = false">取 消</el-button>
          <el-button v-preventReClick type="primary" @click="chiceChange">确 定</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  addUser,
  changeUserStatus,
  delUser,
  exportUser,
  getUser,
  importTemplate,
  setUserPwd,
  updateUser,
  isOnlyEnterprise
} from "@/api/system/user";

import {
 listUser
} from "@/api/common/user";
import {listSimpleMenus} from "@/api/system/menu";
import {assignRoleMenu, listRoleMenus, assignRoleDataScope} from "@/api/system/permission";
import {listSimpleDepts,delDept,updateDept} from "@/api/system/dept";
import {CommonStatusEnum, SystemDataScopeEnum} from "@/utils/constants";
import {DICT_TYPE, getDictDatas} from "@/utils/dict";
// 组织结构树组件
import orgstructure from './components/organizationstructure.vue'
//添加用户
import Adduser from './components/adduser.vue'
//操作离职
import Resignation from './components/Resignation.vue'
//人员变更
import PersonChange from './components/PersonChange.vue'
//部门管理
import deptManage from '../system/dept/index'
export default {
  name: "SystemRole",
  components:{orgstructure,Adduser,Resignation,PersonChange,deptManage},
  data() {
    return {
      titleShow:'',
      dataSure:{},
      nodeSure:{},
      command:'',
      dialogShow:false,
      onlyManger:false,
      dialogVisible:false,
      isClick:true,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色表格数据
      userList: [],
      // 弹出层标题
      title: "",
      titleUser:"",
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      // 是否显示弹出层（菜单权限）
      openMenu: false,
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      // 菜单列表
      menuOptions: [],
      // 部门列表
      deptID:undefined,
      deptOptions: [], // 部门属性结构
      depts: [], // 部门列表
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        username: undefined,
        deptId: undefined,
        show:true
        //show:undefined
      },
      // 表单参数
      form: {},
      defaultProps: {
        label: "name",
        children: "children"
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "角色名称不能为空", trigger: "blur" }
        ],
        code: [
          { required: true, message: "角色标识不能为空", trigger: "blur" }
        ],
        sort: [
          { required: true, message: "角色顺序不能为空", trigger: "blur" }
        ],
        SelectedDepartment:[],//点击被选中的部门名称
      },
      //人员变更、操作离职的禁用变量
      btnselectData:[],
      //被选中的行id
      idChoice:0,
      // 枚举
      SysCommonStatusEnum: CommonStatusEnum,
      SysDataScopeEnum: SystemDataScopeEnum,
      // 数据字典
      roleTypeDictDatas: getDictDatas(DICT_TYPE.SYSTEM_ROLE_TYPE),
      statusDictDatas: getDictDatas(DICT_TYPE.COMMON_STATUS),
      dataScopeDictDatas: getDictDatas(DICT_TYPE.SYSTEM_DATA_SCOPE)
    };
  },
  methods: {
    /** 查询角色列表 */
    getList() {
      this.loading = true;
      console.log(this.queryParams.deptId,'00011');
     // debugger
     if(!this.queryParams.deptId){
      listSimpleDepts().then(response => {
        response.data.forEach((item,index) => {
          Object.assign(item,{sort:index})
        })
        // 处理 deptOptions 参数
        this.deptOptions = [];
        this.deptOptions.push(...this.handleTree(response.data, "id"));
        this.queryParams.deptId=this.deptOptions[0].id
        })
     };   
      listUser(this.queryParams).then(
        response => {
          this.userList = response.data.list;
          this.total = response.data.total;
          this.loading = false;
        }
      );
    },
    /**组织结构回调 */
    emitParentGlobalThis(deptId,node,type){
      if(type==false){
        this.isClick=true
        return
      }
      this.queryParams.deptId = deptId
      this.deptID = deptId
      this.reset()
      if(node){
       // if(node.childNodes.length==0){
        this.isClick=false
        this.SelectedDepartment = node.data
     //  }
      }   
    },
    refreshTree(){
      console.log('刷新了')
      this.$refs.org.getTreeselect()
    },
    updateSure(data,node,command,sortMax,sort){
      console.log(data,node,command,'00000')
      this.dataSure = data
      this.nodeSure = node
      this.command = command
      if(command =="d"){
        this.titleUser = "确定删除此组织？"
        this.dialogVisible = true
      }else{
        data.parentName=node.parent.data.id//之前Id和name互换一下，不想改代码了
        data.parentId=node.parent.data.name
        console.log(node.parent.data.name,data.parentId)
        this.$refs.deptM.handleAdd(data,command,sortMax,sort)
      }
    },
    /**组织结构选择不同的操作*/
    chiceChange(data,node,command){
      console.log(data,'id-chiceChange---')
      switch (command) {
        case "a":
          delDept(data.id).then(response=>{
            console.log(response,'responseshanchu---88')
          })
          break;
        case "b":
          delDept(id).then(response=>{
            console.log(response,'responseshanchu---88')
          })
          break;
        case "c":
            let from ={
            name: data.name,
            sort: data.sort,
            hasChildren: node.childNodes.length>0?true:false,
            status:0,
            id: data.id,
          }
          updateDept(from).then(response=>{
            console.log(response,'responseshanchu')
          })
          break;
        case "d":
          // delDept(data.id).then(response=>{
          //   console.log(response,'responseshanchu---88')
          // })删除
          break;
      
        default:
          break;
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$refs.adduser.handleadd('0',this.SelectedDepartment)
    },
    // 操作离职按钮
    handlereg(){
      this.$refs.reg.handlereg(this.btnselectData)
    },
    //人员变更按钮
    handlePersonChange(){
      this.$refs.PersonChange.handleadd(this.btnselectData[0])
    },
    /**修改密码 */
    handleedit(row){
      this.titleUser="确定重置用户密码？"
      this.dialogVisible=true
      this.idChoice=row.id
    },
   
    update(){
      this.dialogVisible = false
      if(this.onlyManger==true){
        return
      }
      if(this.titleUser=='确定重置用户密码？'){
          setUserPwd({id:this.idChoice}).then(response => {
            this.$modal.msgSuccess("重置密码成功");
          });
      }else if(this.titleUser == '确定删除此组织？'){
         delDept(this.dataSure.id).then(response=>{
            this.$modal.msgSuccess("删除组织成功");
            this.$refs.org.getTreeselect()
            console.log(response,'responseshanchu---88')
          })
      }else{
        delUser(this.idChoice).then(response => {
          this.$modal.msgSuccess("删除用户成功");
          this.reset();
        })
      }
    },
    //前往人员变更
    Routerinsidepersonchange(){
      this.$router.push('/organization/insidepersonchange')
    },
    //前往操作离职
    Routerinsidereg(){
      this.$router.push('/organization/insidereg')
    },
    //表格select
    handleSelectionChange(val){
      console.log(val,'val--')
      // if(val.length == this.userList.length){
      //   this.$refs.table.clearSelection();         
      //   return
      // }
       if (val.length > 1) {         
        this.$refs.table.clearSelection(); 
        val = val.pop()       
        this.$refs.table.toggleRowSelection(val,true);   
        this.btnselectData=[]
        this.btnselectData.push(val)
        return
      }
      this.btnselectData = val
    },
    // 角色状态修改
    handleStatusChange(row) {
      // 此时，row 已经变成目标状态了，所以可以直接提交请求和提示
      let text = row.status === CommonStatusEnum.ENABLE ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.name + '"角色吗?').then(function() {
          return changeRoleStatus(row.id, row.status);
        }).then(() => {
          this.$modal.msgSuccess(text + "成功");
        }).catch(function() {
          // 异常时，需要将 row.status 状态重置回之前的
          row.status = row.status === CommonStatusEnum.ENABLE ? CommonStatusEnum.DISABLE
              : CommonStatusEnum.ENABLE;
        });
    },

    // 取消按钮（数据权限）
    cancelDataScope() {
      this.openDataScope = false;
      this.reset();
    },
    // 取消按钮（菜单权限）
    cancelMenu() {
      this.openMenu = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.queryParams.pageNo = 1
      this.handleQuery();
    },
    /** 重置按钮操作 */
    resetQuery() {
      // this.queryParams.username=undefined
      // this.queryParams.mobile=undefined
      // this.queryParams.nickname=undefined
      this.queryParams= {
        pageNo: 1,
        pageSize: 10,
        username: undefined,
        show:true,
        mobile:undefined,
        nickname:undefined,
        deptId:this.deptID
      }
      //this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      if (type === 'menu') {
        let treeList = this.menuOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
        }
      } else if (type === 'dept') {
        let treeList = this.deptOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value;
        }
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      if (type === 'menu') {
        this.$refs.menu.setCheckedNodes(value ? this.menuOptions: []);
      } else if (type === 'dept') {
        // this.$refs.dept.setCheckedNodes(value ? this.deptOptions: []);
        this.$refs.dept.setCheckedNodes(value ? this.depts: []);
      }
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      if (type === 'menu') {
        this.form.menuCheckStrictly = value;
      } else if (type === 'dept') {
        this.form.deptCheckStrictly = !value;
      }
    },

    /** 分配菜单权限操作 */
    handleMenu(type,row){
      this.$refs.adduser.handleadd(type,row.id)
      console.log(row,'row----')
      this.reset();
    },
    /** 分配数据权限操作 */
    handleDataScope(row) {
      this.reset();
      // 处理了 form 的角色 name 和 code 的展示
      this.form.id = row.id;
      this.form.name = row.name;
      this.form.code = row.code;
      // 打开弹窗
      this.openDataScope = true;
      // 获得部门列表
      listSimpleDepts().then(response => {
        // 处理 deptOptions 参数
        this.deptOptions = [];
        this.deptOptions.push(...this.handleTree(response.data, "id"));
        this.depts = response.data;
        // this.deptIds = response.data.map(x => x.id);
        // 获得角色拥有的数据权限
        getRole(row.id).then(response => {
          this.form.dataScope = response.data.dataScope;
          this.$refs.dept.setCheckedKeys(response.data.dataScopeDeptIds, false);
        });
      });
    },

    /** 提交按钮（数据权限） */
    submitDataScope: function() {
      if (this.form.id !== undefined) {
        assignRoleDataScope({
          roleId: this.form.id,
          dataScope: this.form.dataScope,
          dataScopeDeptIds: this.form.dataScope !== SystemDataScopeEnum.DEPT_CUSTOM ? [] :
              this.$refs.dept.getCheckedKeys()
        }).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.openDataScope = false;
          this.getList();
        });
      }
    },
    /** 提交按钮（菜单权限） */
    submitMenu: function() {
      if (this.form.id !== undefined) {
        assignRoleMenu({
          roleId: this.form.id,
          menuIds: [...this.$refs.menu.getCheckedKeys(), ...this.$refs.menu.getHalfCheckedKeys()]
        }).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.openMenu = false;
          this.getList();
        });
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.titleUser="确认删除此用户？"
      this.dialogVisible=true
      isOnlyEnterprise(row.id).then(response => {
        if(response.data==0){
          this.onlyManger = false;
        }else{
          this.onlyManger = true
        }
      });
      this.idChoice=row.id
      console.log(row,'row-----')
    },
    /** 批量导入用户按钮操作 */
    handleExport() {
      //const queryParams = this.queryParams;
        this.$store.dispatch('uploads/SETOPEN',true)
        this.$store.dispatch('uploads/SETTYPE',1)
        this.$store.dispatch('uploads/SETACTIVE',0)
        this.$store.dispatch('uploads/SETTITLE','批量导入用户')
    }
  }
};
</script>


<style lang="scss" scoped>
::v-deep .el-checkbox__inner{
  border-radius: 50%;
}
.isPluralistic{
    color: #fff;
    background-color: #1257FF;
    border-color: #1257FF;
    padding:1px 2px;
    font-size: 12px;
    border-radius: 5px;
    box-sizing: border-box;
}
</style>